package com.tt.fashionWebSite.service.imp;

import com.tt.fashionWebSite.dao.DanhMucBaiVietDao;
import com.tt.fashionWebSite.domain.DanhMucBaiViet;
import com.tt.fashionWebSite.dto.DanhMucBaiVietDto;
import com.tt.fashionWebSite.dto.JsonResponseCode;
import com.tt.fashionWebSite.service.Ad_PostCategoryService;
import com.tt.fashionWebSite.service.GenericService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("ad_postCategoryService")
public class Ad_PostCategoryServiceImp extends GenericService implements Ad_PostCategoryService {
    @Autowired
    @Qualifier("danhMucBaiViet")
    private DanhMucBaiVietDao danhMucBaiVietDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int adminPostCategory(DanhMucBaiVietDto postCategoryDto) {
        DanhMucBaiViet danhMucBaiViet = danhMucBaiVietDao.findById(postCategoryDto.getMaDMBV());
        if(danhMucBaiViet == null){
            danhMucBaiViet = new DanhMucBaiViet();
            danhMucBaiViet.setMaDMBV(postCategoryDto.getMaDMBV());
            danhMucBaiViet.setTenDM(postCategoryDto.getTenDM());
            danhMucBaiVietDao.insert(danhMucBaiViet);
            return JsonResponseCode.SUCCESS;
        }
        else {
            return JsonResponseCode.FAILED;
        }
    }

    public List<DanhMucBaiVietDto> getAllCategory () {
        return mapper.mapCollection(danhMucBaiVietDao.getPostCategory(), DanhMucBaiVietDto.class);
    }

    public DanhMucBaiVietDto getPostCategoryInfoEdit(DanhMucBaiVietDto categoryDto){
        DanhMucBaiViet danhMucBaiViet = danhMucBaiVietDao.findById(categoryDto.getMaDMBV());
        DanhMucBaiVietDto danhMucBaiVietDto = mapper.map(danhMucBaiViet, DanhMucBaiVietDto.class,DANH_MUC_BAI_VIET_MAP_ID);
        return  danhMucBaiVietDto;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public DanhMucBaiVietDto registerPostCategoryEdit(DanhMucBaiVietDto categoryDto) {
        DanhMucBaiViet danhMucBaiViet = danhMucBaiVietDao.findById(categoryDto.getMaDMBV());
        try {
            danhMucBaiViet.setMaDMBV(categoryDto.getMaDMBV());
            danhMucBaiViet.setTenDM(categoryDto.getTenDM());
            danhMucBaiVietDao.update(danhMucBaiViet);
            return categoryDto;
        }
        catch (Exception ex) {
            return null;
        }
    }
}

